﻿using System.Text.Json;
using Grpc.Net.Client;
using Grpc.Net.ClientFactory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ProtoBuf.Grpc.Client;
using ProtoBuf.Grpc.ClientFactory;
using Shared;

IServiceCollection service = new ServiceCollection();

//注册客户端工厂
service.AddCodeFirstGrpcClient<IOrderService>(o =>
{
    o.Address = new Uri("http://localhost:5001");
    o.InterceptorRegistrations.Add(new InterceptorRegistration(InterceptorScope.Channel, _ => new ClientLoggerInterceptor(new LoggerFactory())));
});
var serviceProvider = service.BuildServiceProvider();

//从客户端工厂创建
using var scope = serviceProvider.CreateScope();
var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
var resp = await orderService.CreateOrderAsync(new CreateOrderReq { Name = "test", Price = 100.01 });
Console.WriteLine(JsonSerializer.Serialize(resp));

//直接从channel创建服务
using var channel = GrpcChannel.ForAddress("http://localhost:5001");
orderService = channel.CreateGrpcService<IOrderService>();
resp = await orderService.CreateOrderAsync(new CreateOrderReq { Name = null, Price = 100.01 });
Console.WriteLine(JsonSerializer.Serialize(resp));